package com.fpost.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.fpost.constants.ActionConstants;
import com.fpost.domain.Article;
import com.fpost.domain.ArticleVersion;
import com.fpost.form.CreateArticleForm;
import com.fpost.form.dto.UserDTO;
import com.fpost.manager.ArticleManager;
import com.fpost.manager.DictionaryManager;
import com.fpost.manager.UserManager;
import com.fpost.security.ActionSecurityUtils;
import com.fpost.util.ActionUtils;
import com.fpost.util.CommonUtils;
import com.fpost.util.DateUtil;
import com.fpost.util.FpostCache;

public class CreateArticleAction extends Action {
	
	private static Logger log = Logger.getLogger(CreateArticleAction.class);
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//set current path in session
		CommonUtils.setCurrentPathInSession(request, mapping);
		
		String forward = ActionConstants.SUCCESS;		

		try { 			
			UserDTO userDTO = ActionSecurityUtils.getUserDTO_fromSession(request);			
			if (userDTO == null) {
				forward = ActionConstants.LOGIN;
			} else {
					
				CreateArticleForm createArticleForm = (CreateArticleForm) form;				
				createArticleForm.setArticleTypeDTOList(FpostCache.getInstance().getArticleTypeDTOList());
			
				String title = createArticleForm.getTitle();
				String keywords = createArticleForm.getKeywords();
				String summary = createArticleForm.getSummary();
				String body = createArticleForm.getBody();
				
				if (title == null && body == null && summary == null) {
					// on first load set authorName property and show empty page					
					createArticleForm.setAuthorFirstName(userDTO.getFirstName());
					createArticleForm.setAuthorLastName(userDTO.getLastName());
					createArticleForm.setAuthorUsername(userDTO.getUsername());
					forward = ActionConstants.RELOAD;
				} else {
					createArticleForm.setAuthorUsername(userDTO.getUsername());
					createArticleForm.setAuthorFirstName(userDTO.getFirstName());
					createArticleForm.setAuthorLastName(userDTO.getLastName());
					
					//article creation time should be the same as its first version creation time
					Date date = DateUtil.getGMTCalendar().getTime();
					
					Article article = new Article();						
					article.setUser(new UserManager().get(Long.parseLong(userDTO.getUserId())));
					article.setCreatedOn(date);
					
					ArticleVersion version = new ArticleVersion();					
					version.setTitle(title);					
					version.setArticleTypeId(Long.parseLong(createArticleForm.getArticleTypeId()));
					version.setCreatedOn(date);
					version.setCreatedIp(request.getRemoteAddr());
					version.setSummary(CommonUtils.replaceLineSeparator(summary));
					version.setBody(CommonUtils.replaceLineSeparator(body));
					version.setKeywords(keywords);
					version.setLatestVersion(true);					
					
					article.getVersions().add(version);
					
					ArticleManager articleManager = new ArticleManager();
					Long articleId = articleManager.save(article);
										
					//add new words to dictionary
					new DictionaryManager().addNewWords(articleId);
					ActionUtils.setErrorMessage(request, "info.article.successfully.created");					
					forward = ActionConstants.SUCCESS;					
				}				
			}
		} catch (NumberFormatException e) {
			log.error(e.getMessage());
			ActionUtils.setErrorMessage(request, "error.article.not.created");
			forward = ActionConstants.FAILURE;	
		} catch (Exception e) {			
			log.error(e.getMessage());
			e.printStackTrace();
			forward = ActionConstants.SYSTEM_FAILURE;
		}

		return mapping.findForward(forward);
	}
    
}
